import os

from config.setting import setting_config  # 引入你的配置

os.makedirs("logs", exist_ok=True)

DEBUG = getattr(setting_config.app, "debug", False)

LOGGING_CONFIG = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "colored": {
            "()": "colorlog.ColoredFormatter",
            "format": "%(log_color)s%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S",
            "log_colors": {
                "DEBUG": "cyan",
                "INFO": "green",
                "WARNING": "yellow",
                "ERROR": "red",
                "CRITICAL": "bold_red",
            },
        },
        "plain": {
            "format": "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S",
        },
        "access": {
            "()": "uvicorn.logging.AccessFormatter",
            "fmt": '%(asctime)s | %(levelname)-8s | %(client_addr)s - "%(request_line)s" %(status_code)s',
            "datefmt": "%Y-%m-%d %H:%M:%S",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "colored" if DEBUG else "plain",  # 👈 根据 debug 切换彩色/普通
        },
        "file_info": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "filename": "logs/app.log",
            "when": "midnight",
            "backupCount": 7,
            "encoding": "utf-8",
            "formatter": "plain",
            "level": "INFO",
        },
        "file_error": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "filename": "logs/error.log",
            "when": "midnight",
            "backupCount": 14,
            "encoding": "utf-8",
            "formatter": "plain",
            "level": "ERROR",
        },
        "file_access": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "filename": "logs/access.log",
            "when": "midnight",
            "backupCount": 7,
            "encoding": "utf-8",
            "formatter": "access",
            "level": "INFO",
        },
    },
    "loggers": {
        "uvicorn":       {"handlers": ["console", "file_info"], "level": "INFO"},
        "uvicorn.error": {"handlers": ["console", "file_info", "file_error"], "level": "INFO", "propagate": False},
        "uvicorn.access": {"handlers": ["file_access", "console"], "level": "INFO", "propagate": False},
        "app":           {"handlers": ["console", "file_info", "file_error"], "level": "DEBUG", "propagate": False},
    },
}
